package com.twfpro.web;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.WebDriverWait;

import com.twfpro.web.Locator.Type;

public abstract class Browser
{
	public WebDriver driver;
	public WebDriverWait driverWait;

	public abstract WebDriver createDriver();

	/**
	 * 打开URL
	 * 
	 * @param url
	 */
	public void openUrl(String url)
	{
		if (driver == null)
		{
			driver = createDriver();
			setTimeout(120);
		}
		driver.get(url);
	}

	/**
	 * 设置超时时间
	 * 
	 * @param time
	 *            超时时间，单位：秒
	 */
	public void setTimeout(long time)
	{
		driver.manage().timeouts().pageLoadTimeout(time, TimeUnit.SECONDS);
		driver.manage().timeouts().setScriptTimeout(time, TimeUnit.SECONDS);
		driverWait = new WebDriverWait(driver, time);
	}

	/**
	 * 获取页面元素
	 * 
	 * @param type
	 *            查找类型
	 * @param value
	 *            类型值
	 * @return Element 对象
	 */
	public Element findElement(Type type, String value)
	{
		return Element.element(this, type, value);
	}

	public ArrayList<Element> findElements(Type type, String value)
	{
		return Element.elements(this, type, value);
	}

	/**
	 * 设置浏览器最大化
	 */
	public void maxWindow()
	{
		driver.manage().window().maximize();
	}

	/**
	 * 刷新浏览器
	 */
	public void refresh()
	{
		driver.navigate().refresh();
	}

	/**
	 * 浏览器后退
	 */
	public void back()
	{
		driver.navigate().back();
	}

	/**
	 * 浏览器前进
	 */
	public void forward()
	{
		driver.navigate().forward();
	}

	/**
	 * 关闭浏览器
	 */
	public void quit()
	{
		driver.quit();
	}

	/**
	 * 截图
	 * 
	 * @param filename
	 *            文件名
	 */
	public void snapshot(String filename)
	{
		TakesScreenshot drivername = (TakesScreenshot) driver;
		String currentPath = System.getProperty("user.dir");
		File scrFile = drivername.getScreenshotAs(OutputType.FILE);
		try
		{
			System.out.println("截图路径:" + currentPath + "/" + filename);
			FileUtils.copyFile(scrFile, new File(currentPath + "\\" + filename));
		}
		catch (IOException e)
		{
			System.out.println("无法截图");
			e.printStackTrace();
		}
		finally
		{
			System.out.println("截图完成");
		}
	}
}
